#!/bin/bash

RED="31"
GREEN="32"
BOLDGREEN="\e[1;${GREEN}m"
ITALIC="\e[3;m"
ENDCOLOR="\e[0m"

function run_cmd()
{
        echo -e "${ITALIC}Running command: $@${ENDCOLOR}"
        eval $@
}

function info()
{
        echo -e "${BOLDGREEN}$@${ENDCOLOR}"
}

info "Shutting down all CEPH process..."
cmd="killall -9 ceph-mgr || killall -9 ceph-mon || killall -9 ceph-osd"
run_cmd "$cmd"

UUID=$(uuidgen)
HOSTIP=$(hostname -i)

info "Removing all previous CEPH setup..."
cmd="rm -rf /etc/ceph/ceph.conf /tmp/ceph.mon.keyring /etc/ceph/ceph.client.admin.keyring /var/lib/ceph/bootstrap-osd/ceph.keyring /tmp/monmap /var/lib/ceph/mon/ceph-$HOSTNAME /var/lib/ceph/mgr/ceph-$HOSTNAME 2>/dev/null"
run_cmd "$cmd"
# Setup ceph.conf
cmd='echo -e "[global]\n
fsid = $UUID\n
mon_initial_members = $HOSTNAME\n
mon_host = $HOSTIP\n
auth_cluster_required = cephx\n
auth_service_required = cephx\n
auth_client_required = cephx\n
osd_pool_default_size = 3\n
osd_pool_default_min_size = 2\n
osd_pool_default_pg_num = 333\n
osd_cruch_chooseleaf_type = 1" > /etc/ceph/ceph.conf'
run_cmd "$cmd"

# Generate keyring for monitor, client.admin, client.bootstrap-osd, and add them to ceph.mon.keyring 
info "Generate keyring..."
cmd="ceph-authtool --create-keyring /tmp/ceph.mon.keyring --gen-key -n mon. --cap mon 'allow *'"
run_cmd "$cmd"
cmd="ceph-authtool --create-keyring /etc/ceph/ceph.client.admin.keyring --gen-key -n client.admin --cap mon 'allow *' --cap osd 'allow *' --cap mds 'allow *' --cap mgr 'allow *'"
run_cmd "$cmd"
cmd="ceph-authtool --create-keyring /var/lib/ceph/bootstrap-osd/ceph.keyring --gen-key -n client.bootstrap-osd --cap mon 'profile bootstrap-osd' --cap mgr 'allow r'"
run_cmd "$cmd"
cmd="ceph-authtool /tmp/ceph.mon.keyring --import-keyring /etc/ceph/ceph.client.admin.keyring"
run_cmd "$cmd"
cmd="ceph-authtool /tmp/ceph.mon.keyring --import-keyring /var/lib/ceph/bootstrap-osd/ceph.keyring"
run_cmd "$cmd"
cmd="chown ceph:ceph /tmp/ceph.mon.keyring"
run_cmd "$cmd"

# Generate a monitor map using the hostname(s), host IP address(es) and the FSID
info "Generate monitor map..."
cmd="monmaptool --create --add $HOSTNAME $HOSTIP --fsid $UUID /tmp/monmap"
run_cmd "$cmd"
# Populate the monitor daemon(s) with the monitor map and keyring
cmd="sudo -u ceph mkdir /var/lib/ceph/mon/ceph-$HOSTNAME"
run_cmd "$cmd"
cmd="sudo -u ceph ceph-mon --mkfs -i $HOSTNAME --monmap /tmp/monmap --keyring /tmp/ceph.mon.keyring"
run_cmd "$cmd"

# Start the monitor(s)
info "Start the monitor(s)..."
cmd="ceph-mon -f --cluster ceph --id $HOSTNAME --setuser ceph --setgroup ceph &"
run_cmd "$cmd"
sleep 5
cmd="sudo -u ceph mkdir /var/lib/ceph/mgr/ceph-$HOSTNAME"
run_cmd "$cmd"
cmd="ceph auth get-or-create mgr.$HOSTNAME mon 'allow profile mgr' osd 'allow *' mds 'allow *'"
run_cmd "$cmd"
cmd="ceph auth get mgr.$HOSTNAME -o /var/lib/ceph/mgr/ceph-$HOSTNAME/keyring"
run_cmd "$cmd"

info "Start the ceph-mgr daemon..."
cmd="ceph-mgr -i $HOSTNAME"
run_cmd "$cmd"

tail -f /dev/null